package com.gitee.beiding.cloud.base.config;

import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.http.client.ClientHttpRequest;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.Charset;
import java.util.Collections;
import java.util.Enumeration;

/*
    公共配置
 */
@Configuration
@ComponentScan(basePackages = "com.gitee.beiding.cloud.base")
public class CommonAutoConfiguration {

    //乱码问题
    @Bean
    public HttpMessageConverter<String> responseBodyConverter() {
        return new StringHttpMessageConverter(Charset.forName("UTF-8"));
    }

    //调用服务,服务间调用一定要使用该方法进行调用,因为该方法会自动copy请求头
    @Bean
    @LoadBalanced
    public RestTemplate serviceRequester() {
        RestTemplate template = new RestTemplate();
        template.setInterceptors(Collections.singletonList(loadBalancedClientHttpRequestInterceptor()));
        return template;
    }

    //调用其他
    @Bean
    public RestTemplate requester() {
        return new RestTemplate();
    }

    private ClientHttpRequestInterceptor loadBalancedClientHttpRequestInterceptor() {
        return (request, body, execution) -> {
            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (requestAttributes != null) {
                HttpServletRequest req = requestAttributes.getRequest();
                ClientHttpRequest clientHttpRequest = (ClientHttpRequest) request;
                HttpHeaders headers = clientHttpRequest.getHeaders();
                Enumeration headerNames = req.getHeaderNames();
                while (headerNames.hasMoreElements()) {
                    String name = (String) headerNames.nextElement();
                    headers.add(name, req.getHeader(name));
                }
            }
            return execution.execute(request, body);
        };
    }


}
